<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Mobile_Pay_module extends CI_Module {

    private $data;
    private $sid;
    private $wx_config;

    public function __construct()
    {
        parent::__construct();
        $this->sid = $GLOBALS['sid'];
        $this->data = $GLOBALS['config'];

        $this->load->model('order.Orderlog_model');
        $this->load->model('order.Orderpaylog_model');
        $this->load->model('order.Ordercontacts_model');
        $this->load->model('order.Orderinfo_model');
        $this->load->model('order.Orderhotel_model');
        $this->load->model('member.User_model');
        $this->load->model('pay.pay_model');
        $this->load->model('weixin.weixin_model');
        $this->wx_config = $this->weixin_model->db_get_setting();

        /*$user_id = $this->session->userdata('user_id');
        if(!$user_id) redirect('mobile/member/oauth');*/

    }

    public function index($id)
    {
        @$user_id = $this->session->userdata('user_id');
        if (!$user_id) redirect(site_url(''));

        $order_id = intval($id);

        $order_info = $this->order_info($order_id);
        $trade_no = $order_info['order_sn'];
        $subject = $order_info['order_title'];
        $total_fee = $order_info['order_account'] - $order_info['paid_account'];
          if (INWECHAT && $GLOBALS['config']['mch_id'])
        {
            $order_info['order_id'] = $order_id;
            $this->session->set_userdata('wxpay_order_info', $order_info);
            redirect(site_url('mobile/pay/wxpay'));
        }
        else
        {
            $this->pay_model->_alipay_m($trade_no, $subject, $total_fee, $order_id);
        }
    }

    public function check_pay()
    {

        $order_id = intval($this->input->get_post('id'));
        $order_info = $this->order_info($order_id);
        $total_fee = $order_info['order_account'] - $order_info['paid_account'];
        if (!($total_fee > 0)) $this->error('订单价格异常！', 1, true);
        if ($order_info['order_status'] == '1') $this->error('订单未审核', 1, true);
        if ($order_info['pay_status'] == '3') $this->error('订单已支付', 1, true);
        $this->success('success', 1, true);
    }


    public function wxpay()
    {
        $this->_wxpay_include_ini();
        $logHandler = new CLogFileHandler(APPPATH . 'logs/' . $this->sid . '/' . date('Y-m-d') . '.log');
        Log::Init($logHandler, 15);
        $order_info = $this->session->userdata('wxpay_order_info');

        if($order_info['order_status'] == '2') //订单已审核 支付订金
        {
            $pay_account = $order_info['earnest_account'];
        }

        if($order_info['order_status'] == '5') //订单已确认 支付订金
        {
            $pay_account = $order_info['order_account'] - $order_info['paid_account'];
        }

        $tools = new JsApiPay();
        $openId = $tools->GetOpenid();
        $input = new WxPayUnifiedOrder();
        $input->SetBody($order_info['order_title']);
        $input->SetAttach($order_info['order_id']);
        $input->SetOut_trade_no($order_info['order_sn'] . date("YmdHis"));
        $input->SetTotal_fee($pay_account * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($order_info['order_title']);
        $input->SetNotify_url(site_url('mobile/pay/wxpay_return_url'));
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $input->SetProduct_id($order_info['order_id']);
        $order = WxPayApi::unifiedOrder($input);
        $this->data['jsApiParameters'] = $tools->GetJsApiParameters($order);
        $this->data['editAddress'] = $tools->GetEditAddressParameters();

        $this->data['title'] = $order_info['order_title'];
        $this->data['check_url'] = site_url('mobile/pay/check_pay_status?id='.$order_info['order_id']);
        $this->data['total_fee'] = intval($order_info['order_account']);

        $this->data['info'] = $order_info;


        $this->load->view(MOBILE_TEMPLATE_NAME . '/' . 'wx_pay', $this->data);
    }

    public function wxpay_return_url()
    {
        $this->_wxpay_include_ini();
        $logHandler = new CLogFileHandler(APPPATH . 'logs/' . $this->sid . '/' . date('Y-m-d') . '.log');
        Log::Init($logHandler, 15);
        Log::DEBUG("begin notify");
        $notify = new PayNotifyCallBack();
        $notify->Handle(false);
        $trade_data = $notify->data;
        Log::DEBUG("trade_data".json_encode($trade_data));
        $order_info = $this->order_info($trade_data["attach"]);
        Log::DEBUG("pay data" . json_encode($order_info));
        if ($trade_data["return_code"] == "SUCCESS" && $trade_data["result_code"] == "SUCCESS")
        {
            if ($order_info['pay_status'] !== 3)
            {
                $this->_pay_finished($trade_data["attach"], $trade_data["cash_fee"]/100);
            }
        }
    }

    private function _wxpay_include_ini()
    {
        define('WX_APPID', $this->wx_config['appid']);
        define('WX_APPSECRET', $this->wx_config['appsecret']);
        define('WX_MCHID', $GLOBALS['config']['mch_id']);
        define('WXPAY_KEY', $GLOBALS['config']['wxpay_key']);
        $wxpay_library = FCPATH . 'application/libraries/wxpay/lib/';
        require_once $wxpay_library . 'WxPay.Exception.php';
        require_once $wxpay_library . 'WxPay.Config.php';
        require_once $wxpay_library . 'WxPay.Data.php';
        require_once $wxpay_library . 'WxPay.Api.php';
        require_once $wxpay_library . 'WxPay.Notify.php';
        require_once $wxpay_library . 'WxPay.JsApiPay.php';
        require_once $wxpay_library . 'log.php';
        require_once $wxpay_library . 'PayNotifyCallBack.php';
        require_once $wxpay_library . 'WxPay.NativePay.php';
        dmkdir(APPPATH . 'logs/' . $this->sid);
    }

    public function alipay_return_url()
    {
        $order_id = $this->uri->segment(4);
        $trade_status = $this->input->get_post('result');   //交易状态
        $order_info = $this->order_info($order_id);
        if ($trade_status == 'success')
        {
            if ($order_info['pay_status'] !== '3')
            {
                if ($this->_pay_finished($order_id, $order_info['order_account']))
                {
                    $this->success('支付成功', $order_info['redirect'], '1');
                }
            }
            else
            {
                $this->success('订单已支付', $order_info['redirect'], '1');
            }
        }
        else
        {
            $this->error('支付失败', $order_info['redirect'], '1');
        }
    }


    public function _pay_finished($order_id, $total_fee)
    {

        $order_info = $this->order_info($order_id);

        // 支付定金
        if($order_info['order_status'] == 2)
        {
            $log_type = 1 ; //游客支付定金
            if($total_fee == $order_info['earnest_account'])   // 更改订单状态为已确认
            {
                $status_data = array(
                    'order_id' => $order_id,
                    'order_status' => 4,
                    'user_type' => '2',
                );
                $this->Orderinfo_model->translate_order_status($status_data);
                $earnest_pay = true;
            }
        }

        // 支付尾款

        if($order_info['order_status'] == 5)
        {
            $log_type = 2 ; //游客支付尾款
            $final_pay = true;
        }

        $log_data = array(
            'pay_account' => $total_fee,
            'order_id' => $order_id,
            'user_type' => '2',
            'type' => $log_type
        );
        $log_res = $this->Orderpaylog_model->save_pay_account($log_data); // 保存支付日志

        if ($log_res)
        {
           if($earnest_pay) //支付定金
           {
               // 通知游客
               $replace = array('sname' => $this->data['company'], 'date' => $order_info['start_date'], 'phone' => $this->data['notify_num']);
               $this->User_model->_send_sms($order_info['mobile'], 'SMS_10820616', $replace);

               // 通知管理员
               $replace = array('sname' => $this->data['company'],'name' => $order_info['name'], 'date' => $order_info['start_date']);
               $this->User_model->_send_sms($this->data['notify_num'], 'SMS_10950002', $replace);
           }

            if ($final_pay) //支付尾款
            {
              /*  // 通知游客
                $replace = array('sname' => $this->data['company'], 'date' => $order_info['start_date'], 'phone' => $this->data['notify_num']);
                $this->User_model->_send_sms($order_info['mobile'], 'SMS_10820616', $replace);

                // 通知管理员
                $replace = array('sname' => $this->data['company'], 'name' => $order_info['name'], 'date' => $order_info['start_date']);
                $this->User_model->_send_sms($this->data['notify_num'], 'SMS_10830608', $replace);*/
            }

        }

    }

    public function check_pay_status()
    {
        $check = false;
        $order_id = intval($this->input->get_post('id'));
        $order_info = $this->Orderinfo_model->get_row(array('order_id' => $order_id));
        if ($order_info['order_status'] == 4 && floatval($order_info['earnest_paid_account']) > 0 && $order_info['pay_status'] == 2)
        {
            $check = true;
        }

        if ($order_info['pay_status'] == 3)
        {
            $check = true;
        }

        if($check){
            echo json_encode(array('status' => 1, 'msg' => 'success'));
        }
        else
        {
            echo json_encode(array('status' => -1, 'msg' => 'fail'));
        }
    }

    public function order_info($order_id)
    {
        $return = array() ;
        $order_info = $this->Orderinfo_model->get_row(array('order_id'=>$order_id));
        $contacts_info = $this->Ordercontacts_model->get_row(array('order_id'=>$order_id));

        if($order_info['order_type']=='1')
        {
            $table = $this->db->dbprefix("order_hotel");
            $order_detail = $this->Orderhotel_model->get_row(array($table.'.order_id'=>$order_id));
            $return = $order_detail;
            $return['order_sn'] = $order_info['order_sn'];
            $return['order_title'] = '农家乐酒店:'.$order_detail['number'].'人';
            $return['start_date'] =  $order_detail['start_date'];
            $return['end_date'] =  $order_detail['end_date'];
            $return['order_num'] =  $order_detail['number'].'人('.$order_detail['male_number'].'男'.$order_detail['woman_number'].'女)';

            $return['order_type'] = $order_info['order_type'] ;
            $return['name'] = $contacts_info['name'] ;
            $return['cat_type'] = $order_info['cat_type'] ;
            $return['order_status'] = $order_info['order_status'] ;
            $return['mobile'] = $contacts_info['phone_num'] ;
            $return['pay_status'] = $order_info['pay_status'] ;
            $return['order_account'] = $order_info['order_account'] ;
            $return['paid_account'] = $order_info['paid_account'] ;
            $return['earnest_account'] = $order_info['earnest_account'] ;
            $return['redirect'] = site_url('mobile/order/hotel_profile/?id='.$order_id);
            $return['goods_url'] = site_url("jingdian/{$order_detail['scenic']}.html");
            $return['add_time'] = $order_info['add_time'];

        }

        return $return ;
    }
}

